package com.spring.mvc.session.client;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

public class ServletRequestWapper extends HttpServletRequestWrapper {
	
	private SessionService sessionService;
	private HttpSession session;
	private String sessionId;

	public ServletRequestWapper(String sessionId, HttpServletRequest request) {
		super(request);
		this.sessionId=sessionId;
		
	}
	public SessionService getSessionService() {
		return sessionService;
	}
	public HttpSession getSession(){
		if(this.session!=null){
			return session;
		}
		return doGetSession(true);
	}
	public void setSessionService(SessionService service2) {
		this.sessionService=service2;
	}
	
	public HttpSession getSession(boolean create){
		if(this.session!=null){
			return this.session;
		}
		return doGetSession(create);
	}
	protected HttpSession doGetSession(boolean create) {
		HttpSession old=super.getSession(create);
		if(old == null){
			return null;
		}
		this.sessionService.createNewSession(this.sessionId, getRealIp());
		this.session=new HttpSessionWapper(this.sessionId,this.sessionService,old);
		return this.session;
	}
	private String getRealIp() {
		try {
			String remoteaddString;
			remoteaddString=super.getRemoteAddr();
			if((remoteaddString.indexOf("192.168.77")>-1) || 
					(remoteaddString.indexOf("192.168.7")>-1) || 
					(remoteaddString.indexOf("192.168.2")>-1)){
				return super.getHeader("X-Forwarded-For").split(",")[0];
			}
			return remoteaddString;
		} catch (Exception e) {
			return super.getRemoteAddr();
		}
	}
}
